<template>
  <el-row>
    <el-col :span="8" :offset="8">
      <div class="change-form">
        <div class="text item">
          <p class="change-title">输入修改用户id</p>
          <el-form :model="change" status-icon ref="change" label-width="80px">
            <el-form-item label="id" prop="id">
              <el-input type="text" v-model="change.id"></el-input>
            </el-form-item>
          </el-form>
          <el-button type="primary" @click="queryBtn" class="changebtn mb-1" style="font-size: 18px;">
             查询
          </el-button>
          <p class="change-title">输入修改信息</p>
          <el-form :model="change" status-icon ref="change" label-width="80px">
            <el-form-item label="头像">
              <el-upload
                action="http://127.0.0.1:5000/add_face_image"
                :data="{ name: change.userName }"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :on-error="handleAvatarError"
              >
                <img v-if="change.avatar" :src="change.avatar" class="avatar-uploader__img">
                <i v-else class="el-icon-plus avatar-uploader__icon"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="用户名" prop="username">
              <el-input type="text" v-model="change.userName"></el-input>
            </el-form-item>
            <el-form-item label="创建时间" prop="username">
              <el-input type="datetime" v-model="change.createTime"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input type="text" v-model="change.password" disabled="disabled"></el-input>
            </el-form-item>
            <el-form-item label="积分" prop="jifenb">
              <el-input type="text" v-model="change.jifen"></el-input>
            </el-form-item>
            <el-form-item label="手机号码" prop="phone">
              <el-input type="text" v-model="change.phone"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input type="email" v-model="change.email"></el-input>
            </el-form-item>
            <el-form-item label="性别" prop="gender">
              <el-select v-model="change.sex" placeholder="请选择">
                <el-option label="男(1)" value="1"></el-option>
                <el-option label="女(0)" value="0"></el-option>
              </el-select>
            </el-form-item>
            <!--<el-form-item label="账号状态" prop="state">-->
              <!--<el-input type="text" v-model="change.state"></el-input>-->
            <!--</el-form-item>-->
          </el-form>
          <el-button :type="btnType" @click="changeBtn" class="changebtn" :disabled="disabled" style="font-size: 18px;">
             确认修改
          </el-button>
        </div>
      </div>
    </el-col>
    <el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
      <span>信息修改成功。</span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false">确定</el-button>
      </span>
    </el-dialog>
  </el-row>

</template>

<script>
  export default {
    data() {
      return {
        oldData:{},
        change: {
          id: '',
          createTime: '',
          userName: '',
          password: '',
          email: '',
          phone: '',
          sex: '',
          jifen: '',
          state: '',
          avatar:'',
        },
        genderRaw: "",
        iconstyle: 'iconfont icon-r-yes',
        disabled: false,
        btnType: 'success',
        isRealchange: false,
        dialogVisible: false,
        nameMap:new Map(),
        faceFile:null,
      }
    },
    mounted(){
      this.getNames();
    },
    components: {},
    methods: {
      handleAvatarSuccess(res, file) {
        console.log(res)
        // 这里简单将文件转换为临时 URL 显示，实际可根据后端返回调整
        this.change.avatar = URL.createObjectURL(file.raw);
        this.faceFile=file.raw;
      },
      handleAvatarError(err, file, fileList) {
        let errorMessage = '上传失败';
        if (err.response && err.response.data && err.response.data.msg) {
          // 如果后端返回的错误信息在 response 的 data 里的 message 字段
          errorMessage = err.response.data.msg;
        } else if (err.message) {
          // 通用的错误信息
          errorMessage = err.message;
        }
        this.$message.warning(errorMessage);
      },
      getNames(){
        fetch("http://127.0.0.1:5000/get_face_dataset_names", {
          method: "get"})
          .then((response) => response.json())
          .then((data) => {
            data.names.forEach(item=>{
              this.nameMap.set(item.split("face_dataset/")[1].split(".jpg")[0],item)
            })
            console.log(this.nameMap)
          })
      },
      changeBtn() {
        this.axios.post("http://localhost:9151/admin/updateUser", this.change)
          .then(res => {
            console.log(res)
            this.dialogVisible = true;
            if (this.oldData.userName !== this.change.userName) {
              var params = { oldname: this.oldData.userName, newname: this.change.userName }
              // 将参数对象转换为查询字符串
              const queryString = Object.keys(params)
                .map(key => encodeURIComponent(key) + '=' + encodeURIComponent(params[key]))
                .join('&');
              const url = `http://127.0.0.1:5000/face_name_update?${queryString}`;
              fetch(url, { method: 'GET' })
                .then(response => response.json())
                .then(data => {
                  console.log(data);
                })
                .catch(error => {
                  console.log('请求出错:', error);
                });
            }
          });
      },
      queryBtn() {
        this.axios.post("http://localhost:9151/admin/getUserById?userId=" + this.change.id)
          .then(res => {
            console.log(res.data.data);
            this.oldData={...res.data.data}
            this.change.createTime = res.data.data.createTime;
            this.change.userName = res.data.data.userName;
            this.change.password = res.data.data.password;
            this.change.email = res.data.data.email;
            this.change.phone = res.data.data.phone;
            this.change.jifen = res.data.data.jifen;
            this.change.state = res.data.data.state;
            this.change.sex = res.data.data.sex;
            this.change.avatar = this.nameMap.has(res.data.data.userName)?"http://"+this.nameMap.get(res.data.data.userName):"https://img1.baidu.com/it/u=2695609535,222024919&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500";
          })
          .catch(res => {
            console.log("err:" + res);
          })
      }
    },
    computed: {
      showgender() {
        if (this.genderRaw == 0)
          return "女";
        else
          return "男";
      }
    }
  }
</script>

<style>
  .change-form {
    margin: 2rem;
  }
  .avatar-uploader__img {
    width: 178px;
    height: 178px;
    display: block;
    border-radius: 10px;
  }
  .avatar-uploader__icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    display: block;
  }
</style>
